package com.easy.auth.controller;

import com.easy.common.bean.SysPermission;
import com.easy.common.bean.SysRole;
import com.easy.common.bean.SysUser;
import com.easy.common.exception.ParameterException;
import com.easy.common.service.IRedisService;
import com.easy.common.service.IUserService;
import com.easy.common.util.JWTUtil;
import com.easy.common.util.PasswordDecode;
import com.easy.common.util.ResultData;
import com.easy.common.util.SYSUtil;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;

@RestController
@RequestMapping("auth")
@CrossOrigin
public class AuthController {
    @DubboReference
    IUserService userService;
    @DubboReference
    IRedisService redisService;
    @PostMapping("login")
    public ResultData login(@RequestBody SysUser user){
        System.out.println(user);

        //获取用户名和密码
        String username=user.getUsername();
        String password=user.getPassword();
        //验证参数
        if(SYSUtil.checkEmpty(username,password)){
            //通过用户名获取用户数据
            //需要访问user模块中的服务
            SysUser sysUser=userService.getByUsername(username);
            if(SYSUtil.checkNull(sysUser)){
                //比较密码
                String password_data=sysUser.getPassword();
                if(PasswordDecode.decode(password,password_data)){
                    //如果成功签发token
                    String token=JWTUtil.generateToken(null);
                    //提取权限和角色组成字符串存入redis
                    String userall=getAllPermission(sysUser);
                    System.out.println(userall);
                    redisService.set(token,userall);
                    return ResultData.success(token);
                }else{
                    throw new RuntimeException("密码不正确");
                }
            }else{
                throw new ParameterException("没有此账号");
            }
        }else{
            throw new ParameterException("参数异常");
        }
        //验证密码是否正确
        //返回对应结果
    }

    private String getAllPermission(SysUser user){
        StringBuilder strb=new StringBuilder();
        for(SysRole role:user.getRoles()){
            strb.append(role.getRolekey());
            strb.append(",");
            for(SysPermission permission:role.getPermissions()){
                strb.append(permission.getPermkey());
                strb.append(",");
            }
        }
        return strb.toString();
    }
}
